package com.salon.modules.sys.service.impl;

import com.salon.common.exception.CustomException;
import com.salon.common.utils.RedisKeys;
import com.salon.common.utils.RedisUtils;
import com.salon.modules.sys.service.ISysCaptchaService;
import com.google.code.kaptcha.Producer;
import java.awt.image.BufferedImage;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

/**
 * 验证码
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl implements ISysCaptchaService {

    @Resource
    private Producer producer;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 生成验证码
     *
     * @param uuid
     * @return
     */
    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new CustomException("uuid不能为空");
        }
        String capText = producer.createText();
        String capStr = capText.substring(0, capText.lastIndexOf("@"));
        String code = capText.substring(capText.lastIndexOf("@") + 1);
        // 验证码存储redis 设置过期时间
        redisUtils.set(RedisKeys.getSysCaptchaKey(uuid), code, 5*60);
        return producer.createImage(capStr);
    }

    /**
     * 验证验证码是否有效
     * @param uuid  uuid
     * @param code  验证码
     * @return
     */
    @Override
    public boolean validate(String uuid, String code) {
        String codeObject = (String) redisUtils.get(RedisKeys.getSysCaptchaKey(uuid));
        if(ObjectUtils.isEmpty(codeObject)) {
            return false;
        }
        if(codeObject.equals(code)) {
            redisUtils.del(RedisKeys.getSysCaptchaKey(uuid));
            return true;
        }
        return false;
    }

}
